from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import Goods
from goods.ser import GoodsSer
from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination
# from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter


# Create your views here.
class MyPage(PageNumberPagination):
    page_size_query_param = 'page_size'  # 如果你写了  /?page_size=5  =>  每页5条
    page_size = 3  # 每页2个


# class GoodsSearchView(APIView):
#     def get(self, request):
#         kw = request.query_params.get('kw')
#         kw_goods = Goods.objects.filter(title__contains=kw)  # query_set
#         if len(kw_goods) == 0:
#             goods3 = Goods.objects.order_by('-show_num')[:3]
#             ser = GoodsSer(goods3, many=True)
#             return Response(ser.data)
#         else:
#             ser = GoodsSer(kw_goods, many=True)
#             return Response(ser.data)


class GoodsModelViewSet(ModelViewSet):
    queryset = Goods.objects.all()
    serializer_class = GoodsSer

    # 指定顾虑的处理器, 哪个方法来处理过滤这个事情
    # 指定过滤方法类, 排序方法类, 一个或多个
    # from django_filters.rest_framework import DjangoFilterBackend
    # from rest_framework.filters import OrderingFilter
    filter_backends = (OrderingFilter,)  # 同时支持过滤和排序

    # 可以排序的字段有哪些, 指定排序字段, 不设置, 排序功能不起效
    ordering_fields = ('show_num',)

    pagination_class = MyPage

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(self, request, *args, **kwargs)
        # 错误示例
        # self.get_object().show_num+=1
        # self.get_object().save()

        # 正确示例
        obj = self.get_object()
        obj.show_num += 1
        obj.save()
        return res

    # /goods/search/?kw=xxx
    @action(methods=['get'], detail=False)
    def search(self, request):
        kw = request.query_params.get('kw')
        kw_goods = Goods.objects.filter(title__contains=kw)  # query_set
        if len(kw_goods) == 0:
            goods3 = Goods.objects.order_by('-show_num')[:3]
            ser = GoodsSer(goods3, many=True)
            return Response(ser.data)
        else:
            ser = GoodsSer(kw_goods, many=True)
            return Response(ser.data)


    # @action(methods=['get'], detail=True)
    # /goods/pk/search/
    # @action(methods=['get'], detail=False)
    # /goods/search/




